package org.orderoid.jsf;

import org.orderoid.ejb.domain.Commande;
import org.orderoid.jsf.util.JsfUtil;
import org.orderoid.jsf.util.PaginationHelper;
import org.orderoid.ejb.facade.CommandeFacade;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import org.orderoid.ejb.domain.Employe;
import org.orderoid.ejb.domain.StatutCommande;
import org.orderoid.ejb.facade.StatutCommandeFacade;

@ManagedBean(name = "commandeController")
@SessionScoped
public class CommandeController implements Serializable {

    private Commande current;
    private DataModel items = null;
    private DataModel itemsTermines = null;
    @EJB
    private org.orderoid.ejb.facade.CommandeFacade ejbFacade;
    private PaginationHelper pagination;
    private PaginationHelper paginationItemsTermines;
    private int selectedItemTermineIndex;
    private int selectedItemIndex;
    @EJB
    private StatutCommandeFacade statutCommandeFacade;
    private String disabled = "true";
    private final String STATUT_REFUSE = "Refusée";
    private String refusRequired = "false";

    public CommandeController() {
    }

    public Commande getSelected() {
        if (current == null) {
            current = new Commande();
            selectedItemIndex = -1;
        }
        return current;
    }

    public Commande getSelectedTermine() {
        if (current == null) {
            current = new Commande();
            selectedItemTermineIndex = -1;
        }
        return current;
    }

    private CommandeFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    HttpSession session = JsfUtil.getCurrentSession();

                    int idRestaurant = (Integer) session.getAttribute("idRestaurant");



                    // return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem()+getPageSize()}));
                    return new ListDataModel(getFacade().listerCommandes(idRestaurant));
                }
            };
        }
        return pagination;
    }

    public PaginationHelper getPaginationItemsTermines() {
        if (paginationItemsTermines == null) {
            paginationItemsTermines = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    //TODO
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    HttpSession session = JsfUtil.getCurrentSession();

                    int idRestaurant = (Integer) session.getAttribute("idRestaurant");



                    // return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem()+getPageSize()}));
                    return new ListDataModel(getFacade().listerCommandesTermines(idRestaurant));
                }
            };
        }
        return paginationItemsTermines;
    }

    public String prepareList() {
        recreateModel();
        recreateModelItemsTermines();
        return "List";
    }

    public String prepareView() {
        current = (Commande) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareViewItemsTermines() {
        current = (Commande) getItemsTermines().getRowData();
        selectedItemTermineIndex = paginationItemsTermines.getPageFirstItem() + getItemsTermines().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Commande();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CommandeCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Commande) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String prepareEditTermine() {
        current = (Commande) getItemsTermines().getRowData();
        selectedItemTermineIndex = paginationItemsTermines.getPageFirstItem() + getItemsTermines().getRowIndex();
        return "Edit";
    }

    public String update() {
        // TODO: Notifier le client si changement de la date de livraison ou en cas de refus
        try {
            getFacade().edit(current);
            /*
             * if ( getFacade().isLivraisonDifferent(current) ) {
             *
             * }
             */
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CommandeUpdated"));
            return prepareList();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Commande) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CommandeDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public DataModel getItemsTermines() {
        if (itemsTermines == null) {
            itemsTermines = getPaginationItemsTermines().createPageDataModel();
        }
        return itemsTermines;
    }

    private void recreateModelItemsTermines() {
        itemsTermines = null;
    }

    public String nextItemsTermines() {
        getPaginationItemsTermines().nextPage();
        recreateModelItemsTermines();
        return "List";
    }

    public String previousItemsTermines() {
        getPaginationItemsTermines().previousPage();
        recreateModelItemsTermines();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    /**
     * Met la commande au statut suivant, selon le statut courant
     */
    public void updateStatut() {
        getFacade().mettreAJourStatut(current);
    }

    // Statistiques
    public String getDateJour() {
        Calendar ca = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        return sdf.format(ca.getTime());
    }

    public Object getTotalCommandes() {
        Integer idResto = (Integer) JsfUtil.getCurrentSession().getAttribute("idRestaurant");
        return getFacade().getTotalCommandes(idResto);
    }

    public Object getTotalCommandesEnCours() {
        Integer idResto = (Integer) JsfUtil.getCurrentSession().getAttribute("idRestaurant");
        return getFacade().getTotalCommandesEnCours(idResto);
    }

    public Object getTotalCommandesFinis() {
        Integer idResto = (Integer) JsfUtil.getCurrentSession().getAttribute("idRestaurant");
        return getFacade().getTotalCommandesFinis(idResto);
    }

    public Object getCAeffectif() {
        Integer idResto = (Integer) JsfUtil.getCurrentSession().getAttribute("idRestaurant");
        if(getFacade().getCAeffectif(idResto) == null){
            return 0;
        }else {
            
           return getFacade().getCAeffectif(idResto); 
        }
    }

    public Object getCAprevisionnel() {
        Integer idResto = (Integer) JsfUtil.getCurrentSession().getAttribute("idRestaurant");
        if(getFacade().getCAprevisionnel(idResto) == null){
            return 0;
        }else {
          return getFacade().getCAprevisionnel(idResto);  
        }
    }

    public Object getCAtotal() {
        Integer idResto = (Integer) JsfUtil.getCurrentSession().getAttribute("idRestaurant");
        if(getFacade().getCAtotal(idResto) == null){
           return 0; 
        }else {
           return getFacade().getCAtotal(idResto); 
        }
    }

    public String commandeAlerte(Date dateLivraison) {
        String ca = "commandeNormale";

        Calendar calendarLivraison = Calendar.getInstance();
        calendarLivraison.setTime(dateLivraison);

        Date maDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(maDate);

        // Il y a un decallage de 2h, je ne sais pas pourquoi
        calendar.add(Calendar.HOUR_OF_DAY, +2);

        if (calendar.compareTo(calendarLivraison) > 0) {
            ca = "commandePerime";
        }

        return ca;
    }

    /**
     * Méthode appelée lorsque le restaurateur change le statut de la commande
     * via la liste déroulante. Action sur le input text "Motif refus"
     */
    public void valueChangeMethod(ValueChangeEvent e) {
        String strStatutCommande = e.getNewValue().toString();

        if (strStatutCommande.equals(STATUT_REFUSE)) {
            disabled = "false";
            refusRequired = "true";
        } else {
            disabled = "true";
            refusRequired = "false";
            //getFacade().
        }
    }

    /*
     * public Boolean isLivraisonDifferent(ValueChangeEvent e) { String
     * strCurrentLivraison = e.getOldValue().toString(); String strNewLivraison
     * = e.getNewValue().toString(); * if ( !
     * strCurrentLivraison.equals(strNewLivraison) ) { return true; } else {
     * return false; } }
     */
    public String getDisabled() {
        return disabled;
    }

    public void setDisabled(String disabled) {
        this.disabled = disabled;
    }

    public String getRefusRequired() {
        return refusRequired;
    }

    public void setRefusRequired(String refusRequired) {
        this.refusRequired = refusRequired;
    }

    @FacesConverter(forClass = Commande.class)
    public static class CommandeControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CommandeController controller = (CommandeController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "commandeController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Commande) {
                Commande o = (Commande) object;
                return getStringKey(o.getIdCommande());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CommandeController.class.getName());
            }
        }
    }
}
